package com.example.demo.config.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.config.consts.LogConst;
import com.example.demo.config.logconfig.LogBack;
import com.example.demo.zhoushengwen.response.ResponseResult;
import com.example.demo.zhoushengwen.utils.RequestUtil;

/**
 * 各种异常转换对应信息
 * 使用默认的HttpStatus枚举
 * 
 * @author  huxing
 * @version  [版本号, 2020年3月19日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@Controller
public class ErrorConvertController implements ErrorController
{
    
    @RequestMapping("/error")
    @ResponseBody
    public ResponseResult handleError(HttpServletRequest request, HttpServletResponse response)
    {
        LogBack.info("CLIENTIP:{}|UUID:{}|position:{}|level:{}|status:{}|desc:{}|error:{}",
            RequestUtil.getCliectIp(request),
            response.getHeader(LogConst.LOG_UUID),
            LogConst.LOG_ERROR_CONVERT_CONTROLLER,
            LogConst.LOG_STATUS_ERROR,
            LogConst.LOG_END,
            ResponseResult.FAIL(getStatus(request)),
            null);
        response.setHeader(LogConst.HANDLE_END, String.valueOf(System.currentTimeMillis()));
        response.setHeader(LogConst.HANDLE_RESULT, ResponseResult.FAIL(getStatus(request)).toString());
        //错误编号已经拿到了，写一个映射转即可，其他业务逻辑
        return ResponseResult.FAIL(getStatus(request));
    }
    
    /**
     * 获取响应状态码
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request)
    {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null)
        {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
    
    @Override
    public String getErrorPath()
    {
        return "/error";
    }
}
